package com.mmall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.IConst;
import com.mmall.common.ResponseInfo;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.service.ICartService;
import com.mmall.util.BigDecimalUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.CartProductVo;
import com.mmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 购物车模块逻辑层实现类
 * Created by qezhhnjy on 2017/10/1-16:16.
 */
@Service("iCartService")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class CartServiceImpl implements ICartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private ProductMapper productMapper;

    //添加到/存在则更新购物车
    @Override
    public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count) {
        if (productId == null || count == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
        Cart tempCart = new Cart();
        if (cart == null) {
            //封装一个购物车信息添加到数据库中
            tempCart.setUserId(userId);
            tempCart.setProductId(productId);
            tempCart.setQuantity(count);
            tempCart.setChecked(IConst.CartConst.CHECKED);
            cartMapper.insert(tempCart);
        } else {
            //存在该购物车,则将count数量商品添加到购物车中
            tempCart.setId(cart.getId());
            tempCart.setQuantity(cart.getQuantity() + count);
            cartMapper.updateByPrimaryKeySelective(tempCart);
        }
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess("添加到购物车成功!", cartVo);
    }

    //更新购物车信息，并返回更新后的完整购物车。应该是在购物车页面对数量进行加减时调用
    @Override
    public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count) {
        if (productId == null || count == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
        if (cart != null) {
            Cart tempCart = new Cart();
            tempCart.setQuantity(count);
            tempCart.setId(cart.getId());
            cartMapper.updateByPrimaryKeySelective(tempCart);
        }
        return ServerResponse.createBySuccess(getCartVoLimit(userId));
    }

    //删除指定购物车信息
    @Override
    public ServerResponse<CartVo> delete(Integer userId, String productIds) {
        //直接将字符串按照指定分隔符分割并转换为集合。
        List<String> productList = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productList))
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        cartMapper.deleteByUserIdProductIds(userId, productList);
        return ServerResponse.createBySuccess(getCartVoLimit(userId));
    }

    //查询指定用户购物车信息
    @Override
    public ServerResponse<CartVo> list(Integer userId) {
        return ServerResponse.createBySuccess(getCartVoLimit(userId));
    }

    //全选or全不选or单选or单独不选
    @Override
    public ServerResponse<CartVo> selectORNot(Integer userId, Integer checked, Integer productId) {
        cartMapper.checkedORNot(userId, checked, productId);
        return list(userId);
    }

    //查询指定用户的购物车商品总件数
    @Override
    public ServerResponse<Integer> getCartProductCount(Integer userId) {
        if (userId == null)
            return ServerResponse.createBySuccess(0);
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
    }

    //通过用户id来完整封装一个该用户的购物车信息的对象CartVo.
    private CartVo getCartVoLimit(Integer userId) {
        CartVo cartVo = new CartVo();
        List<com.mmall.pojo.Cart> carts = cartMapper.selectCartsByUserId(userId);
        List<CartProductVo> cartProductVos = Lists.newArrayList();

        BigDecimal cartTotalPrice = new BigDecimal("0");
        //设置是否被全选的旗标
        boolean allChecked = true;

        if (CollectionUtils.isNotEmpty(carts)) {
            for (com.mmall.pojo.Cart cart : carts) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cart.getId());
                cartProductVo.setUserId(cart.getUserId());
                cartProductVo.setProductId(cart.getProductId());

                Product product = productMapper.selectByPrimaryKey(cart.getProductId());
                if (product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductStock(product.getStock());
                    //判断库存
                    int buyLimitCount = 0;
                    if (product.getStock() >= cart.getQuantity()) {
                        //库存足够
                        buyLimitCount = cart.getQuantity();
                        cartProductVo.setLimitQuantity(IConst.CartConst.LIMIT_NUM_SUCCESS);
                    } else {
                        buyLimitCount = product.getStock();
                        cartProductVo.setLimitQuantity(IConst.CartConst.LIMIT_NUM_FAIL);
                        //将购物车中的商品数量更新为库存量
                        Cart tempCart = new Cart();
                        tempCart.setQuantity(buyLimitCount);
                        tempCart.setId(cart.getId());
                        cartMapper.updateByPrimaryKeySelective(tempCart);
                    }
                    //将判断后的商品购买量赋值给VO
                    cartProductVo.setQuantity(buyLimitCount);
                    //计算该单个购物车的总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.multiply(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                    //勾选状态赋值
                    cartProductVo.setProductChecked(cart.getChecked());
                    //检查勾选状态，是则将该商品总价格增加到CartVo中去。
                    if (cart.getChecked() == IConst.CartConst.CHECKED) {
                        cartTotalPrice = cartTotalPrice.add(cartProductVo.getProductTotalPrice());
                    } else if (allChecked) allChecked = false;
                }
                cartProductVos.add(cartProductVo);
            }
        }
        //完整的购物车VO对象赋值
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVos(cartProductVos);
        cartVo.setAllChecked(allChecked);
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return cartVo;
    }

    @Test
    public void tt() {
        int i = cartMapper.selectCartProductCount(25);
        System.out.println(i);
    }
}
